package com.syezon.wifikey.cengwang;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.SpanUtils;
import com.syezon.android.base.adapter.CommonAdapter;
import com.syezon.android.base.adapter.base.ViewHolder;
import com.syezon.android.base.netstatus.NetUtils;
import com.syezon.wifikey.R;
import com.syezon.wifikey.analysis.AnalysisHelper;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.wifikey.cengwang.viewmodel.TerminalViewModel;
import com.syezon.wifikey.utils.StatusBarUtil;
import com.syezon.wifikey.utils.Utils;
import com.syezon.wifikey.utils.WifiUtil;
import com.syezon.wifikey.web.WebHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class CengwangTestActivity extends BaseActivity {

    @BindView(R.id.ll_top)
    LinearLayout mLlTop;

    @BindView(R.id.iv_retest)
    ImageView mIvRefresh;

    @BindView(R.id.iv_net_indicator)
    ImageView mIvNetIndicator;
    @BindView(R.id.tv_wifi_name)
    TextView mTvWifiName;
    @BindView(R.id.tv_device_count)
    TextView mTvDeviceCount;
    @BindView(R.id.pb_loadding)
    ProgressBar mPbLoading;
    @BindView(R.id.rv_list)
    RecyclerView mRvTerminalList;

    private TerminalViewModel mTerminalViewModel;
    private CommonAdapter<WiFiTerminalUtils.TerminalInfo> mTerminalAdapter;
    private List<WiFiTerminalUtils.TerminalInfo> mData = new ArrayList<>();

    private ValueAnimator mAinim;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.app_tools_cengwang_activity;
    }


    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setPaddingSmart(this, mLlTop);
        mAinim = ObjectAnimator.ofInt(0, 100);
        mAinim.setDuration(5000);
        mAinim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int animatedVaule = (int) animation.getAnimatedValue();
                mPbLoading.setProgress(animatedVaule);
            }
        });
        mTerminalAdapter = new CommonAdapter<WiFiTerminalUtils.TerminalInfo>(mContext, R.layout.item_terminal_layout, mData) {
            @Override
            protected void convert(ViewHolder holder, WiFiTerminalUtils.TerminalInfo terminalInfo, int position) {
                holder.setText(R.id.tv_ip, terminalInfo.getIp())
                        .setText(R.id.tv_mac, terminalInfo.getMac())
                        .setText(R.id.tv_index, position + 1 + "");
                if (terminalInfo.getType() == WiFiTerminalUtils.TerminalInfo.TYPE_UNKNOWN) {
                    holder.setImageResource(R.id.iv_device_type, R.drawable.app_cengwang_normal);
                }
                if (terminalInfo.getType() == WiFiTerminalUtils.TerminalInfo.TYPE_MOBILE) {
                    holder.setImageResource(R.id.iv_device_type, R.drawable.app_cengwang_mobile);
                }
                if (terminalInfo.getType() == WiFiTerminalUtils.TerminalInfo.TYPE_PC) {
                    holder.setImageResource(R.id.iv_device_type, R.drawable.app_cengwang_pc);
                }
                if (terminalInfo.getType() == WiFiTerminalUtils.TerminalInfo.TYPE_EXCHANGE) {
                    holder.setImageResource(R.id.iv_device_type, R.drawable.app_cengwang_gateway);
                }
                if (terminalInfo.getType() == WiFiTerminalUtils.TerminalInfo.TYPE_MONITOR) {
                    holder.setImageResource(R.id.iv_device_type, R.drawable.app_cengwang_monitoring);
                }
            }
        };
        mRvTerminalList.setLayoutManager(new LinearLayoutManager(mContext));
        mRvTerminalList.setAdapter(mTerminalAdapter);
        mTerminalViewModel = ViewModelProviders.of(this).get(TerminalViewModel.class);
        mTerminalViewModel.getTerminalLiveData().observe(this, new Observer<List<WiFiTerminalUtils.TerminalInfo>>() {
            @Override
            public void onChanged(@Nullable List<WiFiTerminalUtils.TerminalInfo> terminalInfos) {
                mData.clear();
                if (terminalInfos != null) {
                    mData.addAll(terminalInfos);
                }
                endScan();
            }
        });
        mTerminalViewModel.getTerminalItemLiveData().observe(this, new Observer<WiFiTerminalUtils.TerminalInfo>() {
            @Override
            public void onChanged(@Nullable WiFiTerminalUtils.TerminalInfo terminalInfo) {
                if (terminalInfo != null) {
                    mData.add(terminalInfo);
                    mTerminalAdapter.notifyItemInserted(mData.size() - 1);
                }
                if (terminalInfo == null) {
                    endScan();
                }
            }
        });
        init();
        AnalysisHelper.onEvent("wifiShareClick");
    }

    private void init() {
        if (!NetUtils.isWifiConnected(Utils.getApp())) {
            showNetErrorDialog();
            return;
        } else {
            startScan();
        }
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        super.onNetworkConnected(type);
        if (NetUtils.NetType.WIFI != type) {
            showNetErrorDialog();
        }
    }

    @Override
    protected void onNetworkDisConnected() {
        super.onNetworkDisConnected();
        showNetErrorDialog();
    }

    private void showNetErrorDialog() {
        NetErrorDialog.show(this, new NetErrorDialog.ConfirmCallBack() {
            @Override
            public void confirm() {
                finish();
            }
        });
    }

    private void startScan() {
        if (!NetUtils.isWifiConnected(Utils.getApp())) {
            showNetErrorDialog();
            return;
        }
        mIvNetIndicator.setImageResource(R.drawable.app_cengwang_net_indicator_normal);
        mTvWifiName.setText(WifiUtil.getWifiSSID());
        mTvDeviceCount.setText("扫描中...");
        mIvRefresh.setVisibility(View.GONE);
        mPbLoading.setVisibility(View.VISIBLE);
        mPbLoading.setProgress(0);
        mTerminalViewModel.getTerminalList();
        mData.clear();
        mTerminalAdapter.notifyDataSetChanged();
        mAinim.start();
    }

    private void endScan() {
        mPbLoading.setVisibility(View.GONE);
        mIvRefresh.setVisibility(View.VISIBLE);
        SpanUtils.with(mTvDeviceCount)
                .append("已有 ")
                .append(mData.size() + " ")
                .setForegroundColor(getResources().getColor(R.color.app_cengwang_count))
                .append("台设备连接此网络")
                .create();
        mTerminalAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.ll_back, R.id.iv_retest, R.id.tv_cengwangtip})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_retest:
                init();
                break;
            case R.id.tv_cengwangtip:
                WebHelper.showCengeangTip(mContext, "防蹭网攻略", "http://res.hodanet.com/upload/sy/20200413/18/1589364184677.html", null);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAinim != null && mAinim.isRunning()) {
            mAinim.cancel();
        }
    }
}
